package com.taptech.doufu.ui.view.topicview;

import android.content.Context;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;

/**
 * Created by Administrator on 2017/4/13/013.
 */
public class MeasuredLinearLayoutManager extends LinearLayoutManager {

    private int maxHeight;

    public MeasuredLinearLayoutManager(Context context) {
        super(context);
        setAutoMeasureEnabled(false);
    }

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
        if (state.getItemCount() <= 0) {
            super.onMeasure(recycler, state, widthSpec, heightSpec);
            return;
        }
        if(maxHeight == 0 && getItemCount() > 0) {
            View child = recycler.getViewForPosition(0);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            child.measure(widthSpec, View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            int height = child.getMeasuredHeight() + getPaddingTop() + getPaddingBottom()
                    + params.topMargin + params.bottomMargin;
            if (getOrientation() == LinearLayoutManager.HORIZONTAL){
                if (height > maxHeight) {
                    maxHeight = height;
                }
            }else{
                int sumHeight = height * getItemCount();
                if (sumHeight > maxHeight) {
                    maxHeight = sumHeight;
                }
            }
        }
        heightSpec = View.MeasureSpec.makeMeasureSpec(maxHeight, View.MeasureSpec.EXACTLY);
        super.onMeasure(recycler, state, widthSpec, heightSpec);
    }




    private int[] mMeasuredDimension = new int[2];



    private boolean isScrollEnabled = true;

    public void setScrollEnabled(boolean flag) {
        this.isScrollEnabled = flag;
    }

    @Override
    public boolean canScrollVertically() {
        //Similarly you can customize "canScrollHorizontally()" for managing horizontal scroll
        return isScrollEnabled && super.canScrollVertically();
//        return false;
    }

}
